package com.luzhikun.filters;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/*
 * @Author liu-miss
 * @Description 权限过滤器(如果没有登录无法访问/user下的所有资源)
 * @Date 21:02 2021/5/4
 * @Param
 * @return
 **/
public class PermissFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {

        HttpServletRequest req = (HttpServletRequest) request;
        String servletPath = req.getServletPath();
        // 若ServletPath以/user开头，那么，这个请求的资源必须登录后才能访问
        if (servletPath.startsWith("/user")) {
            HttpSession session = req.getSession(false);
            // 若session不为null，则需要判断user
            // 若Session为null，则直接转到登录页面
            if (session != null) {

                String user = (String) session.getAttribute("user");
                // 若获取的这个user参数值不为null，则直接放行
                if (user != null) {
                    chain.doFilter(request, response);
                } else {
                    // 若获取的user参数为null，则转到登录界面
                    req.getRequestDispatcher("/login.jsp").forward(request, response);
                }

            } else {
                // 若获取的session为null，直接转到登录界面啊
                req.getRequestDispatcher("/login.jsp").forward(request, response);
            }
        } else {
            // 如果这个资源路径不是以/user开头，则放行
            chain.doFilter(request, response);
        }

    }

    @Override
    public void destroy() {

    }
}
